//
//  SYHomeController.m
//  MicroNews
//
//  Created by tongcheng on 15/10/29.
//  Copyright © 2015年 siyue. All rights reserved.
//

#import "SYHomeController.h"
#import "Channel.h"
#import "ChannelLabel.h"
#import "ChannelViewCell.h"
//#import "NewsTableViewController.h"
#import "SYShowNewsController.h"
#import "SYChannelController.h"
#import "UIViewController+MMDrawerController.h"
#import "OrderButton.h"
#import "OrderViewController.h"


//上面滑动栏的高度
#define smallScrollMenuH  40
#define kNavigationbarH  64
@interface SYHomeController()<UICollectionViewDataSource, UICollectionViewDelegate, ChannelLabelDelegate>

{
//    OrderViewController * orderVC;
    
}
@property (nonatomic,strong)OrderViewController *orderVC;

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIButton *channelClick;
@property (weak, nonatomic) IBOutlet UIButton *userBtn;

@property (nonatomic, strong) NSArray *channleList;

@property (weak, nonatomic) IBOutlet UIScrollView *channelView;

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *layout;

@property (nonatomic, assign) NSInteger currentIndex;

@property(nonatomic,assign)BOOL update;

/** 小的滑动视图 */
@property (nonatomic,weak) UIScrollView *smallScroll;
@property (strong,nonatomic)OrderButton *orderButton;

@end

@implementation SYHomeController

- (UIScrollView *)smallScroll
{
    if (_smallScroll == nil){
        UIScrollView *smallScroll=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, smallScrollMenuH)];
        [self.view addSubview:smallScroll];
        smallScroll.showsHorizontalScrollIndicator=NO;
        smallScroll.showsVerticalScrollIndicator=NO;
        self.smallScroll=smallScroll;
        
        UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, smallScrollMenuH)];
        topView.backgroundColor = SYRandomColor;
        self.navigationItem.titleView = topView;
    }
    return _smallScroll;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    
    self.update = YES;
//    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    //将图层的边框设置为圆脚
    self.userBtn.layer.cornerRadius = self.userBtn.width / 2;
    self.userBtn.layer.masksToBounds = YES;
    
    self.userBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    self.userBtn.layer.borderWidth = 2/[UIScreen mainScreen].scale;
    
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    
    [self loadChannleData];
//    NSLog(@"%s -- %@",__func__,NSStringFromCGRect(self.collectionView.frame));
    [ self.userBtn addTarget:self action:@selector(didUserClick:) forControlEvents:UIControlEventTouchUpInside];
    [ self.channelClick addTarget:self action:@selector(didChannelClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = nil;
    

    
}


- (void)didUserClick:(UIButton *)sender
{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:^(BOOL finished){}];
}

- (void)didChannelClick:(UIButton *)sender
{
//    SYChannelController *channel = [[SYChannelController alloc] init];
//    channel.arrayChannel = self.channleList;
//    channel.title = @"频道管理";
//    [self.navigationController pushViewController:channel animated:YES];
    
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    
    
    [self.mm_drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeNone];
//    OrderButton * orderButton = (OrderButton *)sender;
    _orderVC = [[OrderViewController alloc] init];
    
    _orderVC.titleArr = @[@"推荐",@"头条",@"娱乐",@"音乐",@"电影",@"八卦",@"订阅",@"就我"];
    _orderVC.urlStringArr = @[@"-2",@"-1",@"44114",@"44",@"4444",@"444",@"-3",@"-4"];
    UIView * orderView = [_orderVC view];

    
//    [_orderVC.backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];

//    [orderView setBackgroundColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1.0]];
    orderView.backgroundColor = [UIColor whiteColor];
    _orderVC.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
//    UIButton  *redBtn = [UIButton buttonWithType:UIButtonTypeCustom];
////    redBtn.bounds =  CGRectMake(0, 0, 46, 31);
//    [redBtn setBackgroundImage:[UIImage imageNamed:@"navi_expend"] forState:UIControlStateNormal];
//    [redBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
//    
//    UIBarButtonItem *redBackBtnItem = [[UIBarButtonItem alloc] initWithCustomView:redBtn];
//    _orderVC.navigationItem.leftBarButtonItem = redBackBtnItem;

//    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationController pushViewController:_orderVC animated:YES];
    
}

//从栏目管理中返回，数据保存，刷新主视图列表
- (void)backAction{//保存数据
    
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeAll];
    [self.mm_drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
    [self.navigationController popToRootViewControllerAnimated:NO];

}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSLog(@"-->SYHomeController--------》%@",self);
    NSLog(@"-->SYHomeController ---父亲-----》%@",self.navigationController);
    NSLog(@"-->SYHomeController ---儿子们-----》%@",self.childViewControllers);
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];

}

// 添加频道数据

- (void)loadChannleData {
    
    // 取消自动缩进
    self.automaticallyAdjustsScrollViewInsets = false;
    self.channelView.showsHorizontalScrollIndicator = false;
    
    CGFloat margin = 8;
    CGFloat x = margin;
    CGFloat height = self.channelView.bounds.size.height;
    
    NSInteger index = 0;
    for (NSDictionary *channel in self.channleList) {
//        NSLog(@"--><#name#>--------》%@",channel);
        ChannelLabel *label = [ChannelLabel channelLabelWithTitle:channel[@"name"]];
        // 设置 frame
        label.frame = CGRectMake(x, 0, label.bounds.size.width, height);
        // 设置代理
        label.delegate = self;
        
        label.tag = index++;
        
        x += label.bounds.size.width;
        //        NSLog(@"%@",NSStringFromCGRect(label.frame));
        [self.channelView addSubview:label];
//        [self.smallScroll addSubview:label];

    }
    
    self.channelView.contentSize = CGSizeMake(x + margin, height);
    
    self.currentIndex = 0;
    
    // 设置第0个标签为选中状态
    ChannelLabel *label = self.channelView.subviews[0];
    label.scale = 1.0;
}


#pragma mark - Data Source

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.channleList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ChannelViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"channelCell" forIndexPath:indexPath];
    
    //    cell.backgroundColor = [UIColor colorWithRed:(arc4random_uniform(256) / 255.0) green:(arc4random_uniform(256) / 255.0) blue:(arc4random_uniform(256) / 255.0) alpha:0.9];
    
    // 添加数据
    cell.urlString = self.channleList[indexPath.item][@"c_id"];
//    NSLog(@"--><#name#>--------》%@",self.channleList[indexPath.item][@"c_id"]);
    if (![self.childViewControllers containsObject:cell.newsVC]) {
        [self addChildViewController:cell.newsVC];
    }
    
    cell.newsVC.title = self.channleList[indexPath.item][@"name"];
//        NSLog(@"%@",self.childViewControllers);
    
    return cell;
}

#pragma mark - delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //防止快速滚动造成标签大小
    self.currentIndex = scrollView.contentOffset.x / scrollView.bounds.size.width;
    
    // 当前选中标签
    ChannelLabel *currentLabel = self.channelView.subviews[self.currentIndex];
    
    // 下一个标签
    NSArray *indexPaths = [self.collectionView indexPathsForVisibleItems];
//    NSLog(@"%@",indexPaths);
    ChannelLabel *nextLabel = nil;
    for (NSIndexPath *path in indexPaths) {
        if (path.item != self.currentIndex) {
            nextLabel = self.channelView.subviews[path.item];
            break;
        }
    }
//    NSLog(@"%@",nextLabel.text);
    // 判断下一个是否存在
    if (nextLabel == nil) {
        return;
    }
    
    // 比例
    CGFloat nextScale = fabs(self.collectionView.contentOffset.x / self.collectionView.bounds.size.width - self.currentIndex);
    
    CGFloat currentScale = 1 - nextScale;
    
//    NSLog(@"%f--%f",nextScale,currentScale);
    currentLabel.scale = currentScale;
    nextLabel.scale = nextScale;
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    self.currentIndex = scrollView.bounds.origin.x / scrollView.bounds.size.width;
    // 计算当前选中标签的中心点
    ChannelLabel *label = self.channelView.subviews[self.currentIndex];
    
    CGFloat offSet = label.center.x - self.channelView.bounds.size.width * 0.5;
    CGFloat maxOffSet = self.channelView.contentSize.width - self.channelView.bounds.size.width;
    
    if (offSet < 0) {
        offSet = 0;
    } else if (offSet > maxOffSet) {
        offSet = maxOffSet;
    }
    [self.channelView setContentOffset:CGPointMake(offSet, 0) animated:YES];
    
}



#pragma mark - channelLabel delegate

- (void)channelLabelDidSelected:(ChannelLabel *)label {
    
//    NSLog(@"%@",label.text);
    
    self.currentIndex = label.tag;
    
    // 滚动到指定位置
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.currentIndex inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}


#pragma mark - lazy load

//- (NSArray *)channleList {
//    
//    if (!_channleList) {
//        _channleList = [Channel channelList];
//    }
//    return _channleList;
//}

- (NSArray *)channleList
{
    if (_channleList == nil) {
        _channleList = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"WD.plist" ofType:nil]];
    }
    return _channleList;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.layout.itemSize = self.collectionView.bounds.size;
    self.layout.minimumInteritemSpacing = 0;
    self.layout.minimumLineSpacing = 0;
    self.layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    // 允许分页
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = false;
    
}

@end
